<template>
    <div>
        <a-select :filter-option="filterOption" :value="companyId" placeholder="选择处置单位" show-search @change="handleChange" >
            <a-select-option  v-if="!userInfo">全部</a-select-option>
            <a-select-option v-for="(item,index) in companyList" :key="'companysId'+index" :value="item.value">
                {{item.label}}
            </a-select-option>
        </a-select>
    </div>
</template>

<script>
    import waste from '../../api/waste'
    import { setDataForLabel } from '../../utils/util'

    export default {
        name: 'SelectCompanyList',
        props:{
            // 是否初始化数据
            isInitData : {
                type : Boolean,
                default : false
            },
            companysId : {
                type : String,
                default : ''
            }
        },
        data() {
            return {
                companyId : '',
                userInfo : this.$store.getters.userInfo,
                companyList: [],
            }
        },
        created() {
            this.initData()
        },
        watch:{
            companysId(){
                this.companyId = this.companysId;
            }
        },
        methods: {
            // 初始化查询数据
            async initData() {
                // 根据当前用户去查询
                let userInfo = this.$store.getters.userInfo;
                if(userInfo.companysId){
                    this.companyId = userInfo.companysId;
                }
                let list = await waste.getCompanyListByUserID()
                this.companyList = setDataForLabel(list, 'id', 'companyName');
                if(this.companyList.length && this.isInitData){
                    let info = this.companyList[0];
                    if(info){
                        this.companyId = info.value;
                        this.$emit('change',info.value,info,null);
                    }
                }
            },
            filterOption: function(input, option) {
                return (
                    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                )
            },
            handleChange : function(value,option) {
                this.companyId = value;
                let info = this.companyList.find((val) => val.value == value);
                this.$emit('change',value,info,option);
            }
        }
    }
</script>

<style scoped>

</style>
